package cn.itcast.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AuthFilter implements GlobalFilter {
    /**
     * 拦截请求
     * 获取参数 ，判断值是否admin
     * 如果不是就拦截
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
//        路径
        String path = request.getURI().getPath();
//        参数
        MultiValueMap<String, String> queryParams = request.getQueryParams();
//        获取参数
        String authorization = queryParams.getFirst("authorization");
        log.info("authorization={}",authorization);
        if(authorization != null && "admin".equals(authorization)){
//            放行
            return chain.filter(exchange);
        }
//        拦截
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
}
